package com.tohours.aia.web.action;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import lombok.Data;
import lombok.EqualsAndHashCode;
import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.util.Assert;

import com.tohours.aia.constants.Constants;
import com.tohours.aia.constants.TohoursUtils;
import com.tohours.aia.constants.WebService;
import com.tohours.aia.entity.Customer;
import com.tohours.aia.entity.GiftLog;
import com.tohours.aia.exception.BusinessException;

@EqualsAndHashCode(callSuper = false)
@InterceptorRefs(@InterceptorRef("adminDefaultStack"))
@Namespace("/")
public @Data class AwardAction extends BaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Customer customer;
	private String giftId;
	private GiftLog giftLog;
	private String mobile;
	private String code;
	
	
	@Action("userCenter")
	public String userCenter() throws IOException{
		String id = (String)super.getSession().getAttribute(Constants.SESSION_USER_ID);
		customer = super.getAwardService().getCustomer(id);
		return super.getOsType() + "_user_center";
	}
	
	@Action("ajaxLoterry")
	public void ajaxLoterry(){
		JSONObject json = new JSONObject();
		try {
			giftLog = super.getAwardService().loterry((String)super.getSession().getAttribute(Constants.SESSION_USER_ID));
			json.put("success", true);
			json.put("loterry", giftLog.getGiftCode());
			json.put("giftId", giftLog.getId());
		} catch (BusinessException e) {
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		super.printToHtml(json.toString());
	}
	
	@Action("giftList")
	public String giftList() throws IOException{
		String customerId = this.getCustomerId();
		customer = super.getAwardService().getCustomer(customerId);
		return super.getOsType() + "_gift_list";
	}
	
	@Action("giftExchangePre")
	public String giftExchangePre() throws IOException{
		Assert.notNull(giftId);
		giftLog = super.getAwardService().getGiftLog(giftId);
		if(giftLog.getExchangeFlag()){
			super.jump("userCenter.action");
			return null;
		}
		customer = super.getAwardService().getCustomer(getCustomerId());
		return super.getOsType() + "_gift_exchange_pre";
	}
	
	
	@Action("ajaxSendMessage")
	public void ajaxSendMessage(){
		Assert.notNull(mobile);
		JSONObject json = new JSONObject();
		if(!TohoursUtils.isMobile(mobile)){
			json.put("success", false);
			json.put("msg", "你输入的手机号码不正确！");
		} else {
			try {
				long code = Math.round(Math.random() * 900000 + 100000);
				Date date = (Date)super.getSession().getAttribute(mobile + "date");
				Calendar c = Calendar.getInstance();
				c.add(Calendar.MINUTE, -1);
				if(date != null && date.after(c.getTime())){
					json.put("success", false);
					json.put("msg", String.format("请再过%s秒发送", (date.getTime() - c.getTime().getTime()) / 1000));
				} else {
					super.getSession().setAttribute(mobile, code + "");
					super.getSession().setAttribute(mobile + "date", new Date());
					TohoursUtils.sendSms(mobile, null, "验证码：" + code);
					json.put("success", true);
				}
			} catch (IOException e) {
				json.put("success", false);
				json.put("msg", e.getMessage());
			}
		}
		super.printToHtml(json.toString());
	}
	
	@Action("giftExchange")
	public void giftExchange(){
		Assert.notNull(code);
		Assert.notNull(mobile);
		Assert.notNull(giftId);
		giftLog = super.getAwardService().getGiftLog(giftId);
		if(!giftLog.getExchangeFlag()){
			customer = super.getAwardService().getCustomer(getCustomerId());
			String sessionCode = (String)super.getSession().getAttribute(mobile);
			if(StringUtils.isNotEmpty(sessionCode) && sessionCode.equals(code)){
				super.getSession().removeAttribute(mobile);
				try {
					String exchangeCode = WebService.reward("youbang", "yb123pass", giftLog.getGiftCode() + "", customer.getCustomerName(), mobile, customer.getSlipNumber());

					//成功兑换
					if (StringUtils.isNotEmpty(exchangeCode)
							&& exchangeCode.length() > 2) {
						giftLog.setExchangeFlag(true);
						giftLog.setExchangeCode(exchangeCode);
						super.getAwardService().editGiftLog(giftLog);
						//发送信息到营销员手机
						TohoursUtils
								.sendSms(
										customer.getSellerPhone(),
										null,
										String.format(
												"%s测试成功",
												customer.getCustomerName()));
						
						super.jump("http://www.tlcrewards.cn/AIA/index.php/Index/index/code/"
								+ new String(Base64.encodeBase64(exchangeCode
										.getBytes())));
					} else {
						String message = "";
						if(StringUtils.isNotEmpty(exchangeCode)){
							if(exchangeCode.indexOf("-1") >= 0){
								message = "用户名密码不正确";
							} else if(exchangeCode.indexOf("-2") >= 0){
								message = "此奖励已申请完";
							} else if(exchangeCode.indexOf("-3") >= 0){
								message = "手机号格式不正确";
							} else if(exchangeCode.indexOf("-4") >= 0){
								message = "姓名不能为空";
							} else if(exchangeCode.indexOf("-5") >= 0){
								message = "保单号不能为空";
							} else if(exchangeCode.indexOf("-6") >= 0){
								message = "保单号不能超过3次";
							} else if(exchangeCode.indexOf("-7") >= 0){
								message = "数据操作失败";
							} else {
								message = "其他未知错误";
							}
						}
						super.printToHtml(String.format("<script>alert('接口返回错误信息：%s');history.back();</script>", message));
					}
				} catch (Exception e) {
					e.printStackTrace();
					super.printToHtml("<script>alert('接口调用失败！');history.back();</script>");
				}
			} else {
				super.printToHtml("<script>alert('验证码错误！');history.back();</script>");
			}
		} else {
			super.printToHtml("<script>alert('该礼品已经兑换过了！');location.href='userCenter.action';</script>");
		}
	}
	
	private String getCustomerId(){
		return (String)super.getSession().getAttribute(Constants.SESSION_USER_ID);
	}
	
	public static void main(String args[]){
	}

}
